/*
 * @Title Client.java
 * @Description
 * @Copyright Copyright(c) 2018
 * @Company com.lizhen
 * @author lizhen
 * @version 0.0.1
 */
package com.lizhen.nio.client;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @author lizhen
 */
public class Client {

    /**
     * @author lizhen
     */
    public Client() {
    }

    /**
     * @author lizhen
     */
    public static void main(String[] args) {
        TimeClient.main(null);
    }

    static class TimeClient {
        private static int port = 8125;
        private static Charset charset = Charset.forName("US-ASCII");
        private static CharsetDecoder decoder = charset.newDecoder();
        private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);

        private static void query(String host) {
            SocketChannel sc = null;
            try {
                sc = SocketChannel.open();
                InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
                sc.connect(isa);
                dbuf.clear();
                sc.read(dbuf);
                dbuf.flip();
                CharBuffer cb = decoder.decode(dbuf);

                System.out.print(isa + " : " + cb);
            } catch (CharacterCodingException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public static void main(String[] args) {
            try {
                String host = InetAddress.getLocalHost().getHostAddress();

                System.out.println("Connect to Host:" + host + ", port:" + port);

                query(host);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

    }

}